<template>
  <div class="siteDetail">
    <div class="siteDetail-header">
      <div class="tree-select">
        <span>当前站点：</span>
        <a-tree-select class="AtreeSelect" v-model:value="selectSiteData" ref="siteDetail_treeSelect" show-search
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" allow-clear
          treeNodeFilterProp="siteName" :fieldNames="{
            children: 'children',
            label: 'siteName',
            value: 'id',
          }" tree-default-expand-all :tree-data="siteData" @select="selectTreeData">
        </a-tree-select>
      </div>
      <a-button type="primary" class="createStaticPage" v-if="0">生成静态页</a-button>
      <!-- <a-button class="previewSite" :disabled="!btnPerm.includes('previewAble')">预览站点</a-button> -->
      <a-popconfirm placement="bottomRight" :ok-text="record.children && record.children.length ? '我知道了' : '确认'"
        cancel-text="取消" :showCancel="record.children && record.children.length ? false : true"
        :disabled="!btnPerm.includes('deleteAble')"
        @confirm="confirmDelete()">
        <template #title>
          <p style="width: 197px">
            {{ deleteTips }}
          </p>
        </template>
        <a-button :disabled="!btnPerm.includes('deleteAble')" class="deleteSite" @click="deleteRecords()">删除站点</a-button>
      </a-popconfirm>
    </div>
    <div class="siteInfoDetail">
      <a-tabs v-model:activeKey="editActiveKey">
        <a-tab-pane key="1" tab="基本设置">
          <div class="a-scroll">
            <base-info :baseInfo="siteBaseInfo[0]" ref="baseInfo_C" class="baseInfo"></base-info>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="扩展设置">
          <div id="a-scroll" class="a-scroll">
            <extend-info :extendInfo="siteExtendInfo[0] ? siteExtendInfo[0] : null" ref="extendInfo_C"
              class="extendInfo"></extend-info>
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="模板设置">
          <div class="a-scroll">
            <tempelteInfo :tempeleteInfo="tempeleteInfo[0] ? tempeleteInfo[0] : null" :siteId="selectSiteData"
              ref="tempeleteInfo_C">
            </tempelteInfo>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <div class="table-bottom_fiexd" :style="styleWidth">
      <a-button type="primary" :disabled="!btnPerm.includes('saveAble')" @click="saveButton">保存</a-button>
      <a-button style="margin-left: 8px;" @click="checkEmail" v-if="editActiveKey == 2">邮箱检测</a-button>
    </div>
    <!-- 邮箱验证模态款 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="extend_modal">
      <template v-slot:body>
        <div>
          <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
            ref="emailCheckFrom" v-if="isVisible">
            <a-form-item :name="['emailCheck', 'value']" :label="formState.emailCheck.label"
              :rules="[formState.emailCheck.rule]">
              <a-input v-model:value="formState.emailCheck.value" allow-clear />
            </a-form-item>
          </a-form>
        </div>
      </template>
    </base-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch, createVNode, nextTick } from "vue";
import baseInfo from "./detail/baseInfo.vue";
import extendInfo from "./detail/extendInfo.vue";
import tempelteInfo from "./detail/tempelteInfo.vue";
import { useRoute } from "vue-router";
import { dataSourceType, detailDataItemType } from "@/type.d";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import request from "@/api/index";
import baseModal from "@/components/modal/baseModal.vue";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import getters from "@/store/getters";
import { Modal, message } from "ant-design-vue";
import {routerPerm} from '@/utils/common';
//type or interface

//data
const btnPerm = ref<any[]>([]);
const routeParams: detailDataItemType = useRoute().query;
const userInfo = getters.userInfo();
//data-header
const siteData = ref<detailDataItemType>([]); //下来选择树
const siteDetail_treeSelect = ref<any>(null);
let record = reactive<detailDataItemType>({});
const selectSiteData = ref<any>(""); // 下拉选择树已选中（当前值值）
const selectSiteData_old = ref<string | number>(""); // 下拉选择树已选中（旧值，用来判断是否数据已经更新，这个时候不得选中，要用旧值);
const deleteTips = ref<String>(""); //站点删除提示语
const errors = ref<number>(0);
//data-baseInfo
const baseInfo_C = ref<any>(null);

const editActiveKey = ref<string | number>("1");
const siteBaseInfo = ref<detailDataItemType>([]);
//data-extendInfo
const extendInfo_C = ref<any>(null);
const siteExtendInfo = ref<detailDataItemType>([]);
//data-tempeleteInfo  
const tempeleteInfo_C = ref();

const tempeleteInfo = ref<detailDataItemType>([]);
// 测试邮箱
const emailCheck = ref<string>('');
const modAlProps: detailDataItemType = reactive({
  width: "M",
  title: "邮箱校验",
});
const emailCheckFrom = ref();
//模态框button按钮个数和文案修改
const buttons = ref<dataSourceType[]>([
  {
    text: "发送",
    "html-type": "submit",
    keepAlive: true,
  },
]);
const isVisible = ref<boolean>(false);
const formState = ref<dataSourceType>({
  emailCheck: {
    value: '',
    rule: {
      required: true,
      trigger: ["blur"],
      message: "收件邮箱不可为空！",
      id: "",
    },
    label: "收件邮箱",
  }
})
//watch
watch(
  () => selectSiteData.value,
  (newVal: string | number, oldVal) => {
    if (oldVal) {
      selectSiteData_old.value = oldVal;
    }
    record = loop(JSON.parse(JSON.stringify(siteData.value)), newVal);
  }
);
watch(
  () => editActiveKey.value,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      newVal == "2" ? getSiteDetail_extendInfo() : getSiteDetail_tempeleteInfo();
    }
  }
);

//methods
// 获取Tree select数据
const getRdecord = async (datas: detailDataItemType = {}) => {
  const data: {} = {
    orgId: userInfo.orgId,
    userId: userInfo.userId,
    allPermissions: true,
  };
  const telData = await request.fetchSiteTreeList(data);
  nextTick(() => {
    siteData.value = [];
    if (telData.length) {
      siteData.value = telData;
      record = loop(JSON.parse(JSON.stringify(siteData.value)), selectSiteData.value);
    }
  });
};
// 删除提示文案变更
const deleteRecords = async () => {
  // 调接口删除站点接口

  if (record.children instanceof Array) {
    deleteTips.value =
      "请将该站点下的子站点编辑按钮重新绑定父级关系或移入回收站，再删除该站点";
  } else {
    deleteTips.value = "删除后的站点可以去站点回收站还原";
  }
};
//确认删除站点
const confirmDelete = async () => {
  // 更改站点开启或关闭状态
  if (record.children instanceof Array) {
    return;
  }
  let params = {
    id: selectSiteData.value,
  };
  await request
    .fetchSiteManageTabledDataMToRecycle(params)
    .then((res: detailDataItemType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRdecord(); // 重新获取tree select 接口
        selectSiteData.value = siteData.value[0].id; //删除站点后默认选择最顶层
        getSiteDetail_baseInfo(); // 重新调取详情接口;
        getSiteDetail_extendInfo();
        getSiteDetail_tempeleteInfo();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 站点基础信息
const getSiteDetail_baseInfo = async () => {
  let data: detailDataItemType = {
    id: selectSiteData.value,
  };
  request.fetchSiteManageGetSiteDetail_baseInfo(data).then((res: dataSourceType) => {
    siteBaseInfo.value = [];
    siteBaseInfo.value.push(res);
  });
};
// 获取站点扩展信息
const getSiteDetail_extendInfo = async () => {
  let data: detailDataItemType = {
    id: selectSiteData.value,
  };
  request
    .fetchSiteManageGetSiteDetail_extendInfo(data)
    .then((res: dataSourceType | null) => {
      siteExtendInfo.value = [];
      siteExtendInfo.value.push(res);
    });
};
// 获取站点模板信息
const getSiteDetail_tempeleteInfo = async () => {
  let data: detailDataItemType = {
    siteId: selectSiteData.value,
  };
  request
    .fetchSiteManageGetSiteDetail_tempeleteInfo(data)
    .then((res: dataSourceType | null) => {
      tempeleteInfo.value = [];
      tempeleteInfo.value.push(res);
    });
};
const selectTreeData = async (value: string | number, node: any) => {
  if (record.id == node.id) {
    // 说明点击了的是当前的已经选中的选项了，无需做数据变动;
    return;
  }
  nextTick(async () => {
    const { newBaseInfo, extendNewValue } = setNewValue();
    let newVal_assign = Object.assign(
      {},
      newBaseInfo,
      {
        scheduleTaskDto: JSON.parse(JSON.stringify(baseInfo_C.value.scheduleTaskDto)),
      },
      extendNewValue
    );
    let oldBaseInfoRecord: dataSourceType = {};
    console.log(selectSiteData_old.value, 99999);
    await request
      .fetchSiteManageGetSiteDetail_baseInfo({ id: selectSiteData_old.value })
      .then((res: dataSourceType) => {
        oldBaseInfoRecord = res;
      });
    let oldExtendInfoRecord: dataSourceType = {};
    await request
      .fetchSiteManageGetSiteDetail_extendInfo({ id: selectSiteData_old.value })
      .then((res: dataSourceType) => {
        oldExtendInfoRecord = res;
      });
    let oldRecord: dataSourceType = Object.assign(
      {},
      oldBaseInfoRecord,
      oldExtendInfoRecord
    );
    let isUpDATE = true;
    const main = (
      data1: dataSourceType,
      data2: dataSourceType,
      arr: (string | number)[] = []
    ) => {
      if (!isUpDATE) {
        return isUpDATE;
      }
      if (typeof data1 == "object") {
        if (Array.isArray(data1)) {
          for (let i = 0; i < data1.length; i++) {
            main(data1[i], data2[i], arr);
          }
        } else {
          for (let key in data1) {
            if (arr.indexOf(key) == -1 && data2.hasOwnProperty(key)) {
              main(data1[key], data2[key], arr);
            } else {
              continue;
            }
          }
        }
      } else {
        isUpDATE = data1 == data2;
      }
      return isUpDATE;
    };
    main(oldRecord, newVal_assign, []);

    if (!isUpDATE) {
      Modal.confirm(
        Object.assign({}, msgModal.confirm, {
          title: "当前设置站点还未保存，是否需要保存?",
          content: "",
          icon: createVNode("i", {
            class: "iconfont icon-warn warning_ICON",
          }),
          okText: "保存",
          class: "siteDetail-modal",
          onOk: async () => {
            //await deleteRecycleRecords({ ids: keys });
            selectSiteData.value = selectSiteData_old.value;
            await saveButton();

            Modal.destroyAll();
          },
          onCancel() {
            //selectSiteData.value = selectSiteData_old.value;
            record = node;
            editActiveKey.value = "1";
            getSiteDetail_baseInfo(); // 重新调取详情接口
            getSiteDetail_extendInfo();
            getSiteDetail_tempeleteInfo();
            Modal.destroyAll();
          },
        })
      );
    } else {
      siteDetail_treeSelect.value.blur();
      record = node;
      editActiveKey.value = "1";
      getSiteDetail_baseInfo(); // 重新调取详情接口
      getSiteDetail_extendInfo();
      getSiteDetail_tempeleteInfo();
    }
  });
};
// 获取已设置的站点最新的基础信息和扩展信息
const setNewValue = () => {
  const newVal = JSON.parse(JSON.stringify(baseInfo_C.value.CCS.formState));
  console.log(newVal, 'newVal')
  newVal.siteDomainAlias = newVal.siteDomainAlias
    .reduce((arr: [string | number], item: dataSourceType) => {
      arr.push(item.value);
      return arr;
    }, [])
    .join(",");
  let newBaseInfo: dataSourceType = {};
  for (let item in newVal) {
    newBaseInfo[item] = newVal[item].value;
    if (item == "status") {
      newBaseInfo[item] = newVal.status?.value ? 1 : 0; // newVal.oldStatus
    }
    if (item == "siteDomainAlias") {
      newBaseInfo[item] = newVal[item];
    }
  }
  delete newBaseInfo.oldStatus;
  const eNV = extendInfo_C.value
    ? JSON.parse(JSON.stringify(extendInfo_C.value.formState))
    : [];
  const extendNewValue: dataSourceType = {};
  eNV?.forEach((item: dataSourceType) => {
    extendNewValue[item.id] = {};
    item.children.forEach((data: dataSourceType) => {
      if (data.hasOwnProperty("param")) {
        if (
          data.param == "newContentResourceUrl" ||
          data.param == "watermarkPictureUrl"
        ) {
          extendNewValue[item.id][data.param] =
            data.value.length === 0 ? null : data.value[0].url;
          extendNewValue[item.id][data.picIdPram] = data.picId;
        } else if (data.param == "greyWhitelist") {
          extendNewValue[item.id][data.param] = [];
          extendNewValue[item.id][data.param].push(data.value);
          if (data.greyWhitelist.length) {
            let otherList = data.greyWhitelist;
            extendNewValue[item.id][data.param] = extendNewValue[item.id][
              data.param
            ].concat(...data.greyWhitelist.map((glist: dataSourceType) => glist.value));
          }
        } else {
          if(data.param == 'uploadFileMemory'){
             if(data.associatedValue == item.children.find((associate:any)=>associate.param=='uploadFileMemoryType').value){
              extendNewValue[item.id][data.param] = data.value;
             }
          }else{
            extendNewValue[item.id][data.param] = data.value === "" ? null : data.value;
          }
          

        }

        if (data.hasOwnProperty("params_options")) {
          extendNewValue[item.id][data.params_options] = data.optionsValue || null;
        }
      }
    });
  });

  return { newBaseInfo, extendNewValue };
};
// 递归处理数据
const loop = (
  datalist: detailDataItemType[] = [],
  value: string | number
): detailDataItemType => {
  // 递归遍历处理数据
  let record: detailDataItemType = {};
  const loop1 = function (data: detailDataItemType[], value: string | number) {
    if (data instanceof Array && data.length) {
      return data.map((d) => {
        if (d.id == value) {
          record = d;
        }
        if (d.children instanceof Array && d.children.length) {
          d.children = loop1(d.children, value);
        }
        return d;
      });
    }
  };
  loop1(JSON.parse(JSON.stringify(datalist)), value);
  return record;
};
//保存数据
const saveButton = async () => {
  const { newBaseInfo, extendNewValue } = setNewValue();
  let newVal_assign = Object.assign({}, newBaseInfo, {
    scheduleTaskDto: JSON.parse(JSON.stringify(baseInfo_C.value.scheduleTaskDto)),
  });
  //return;
  if (editActiveKey.value == 1) {
    let baseForm = baseInfo_C.value.CCS.createSiteFrom;
    baseForm.validate().then(() => {
      let params = Object.assign({ id: selectSiteData.value }, newVal_assign);
      request
        .fetchSiteManageTabledEditBaseInfoRecord(params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getSiteDetail_baseInfo(); // 重新调取详情接口;
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    });
  } else if (editActiveKey.value == 2) {
    let extendForm = extendInfo_C.value.getbaseForm.baseForm;
    extendForm
      .validate()
      .then(() => {
        let params = Object.assign({ id: selectSiteData.value }, extendNewValue);
        console.log(params,'params');
        request
          .fetchSiteManageTabledEditExtendInfo(params)
          .then((res: dataSourceType) => {
            if (res.code == "00000 00000") {
              message.success(res.message);
              getSiteDetail_extendInfo();
              getSiteDetail_tempeleteInfo();
            } else {
              message.error(res.message);
            }
          });
      })
      .catch((err: any) => {
        setTimeout(() => {
          let errors = document.querySelector(".ant-form-item-explain-error");
          if (document.querySelector(".baseInfo")?.contains(errors)) {
            editActiveKey.value = "1";
          } else if (document.querySelector(".extendInfo")?.contains(errors)) {
            editActiveKey.value = "2";
          }
          errors?.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }, 40);
      });
  } else if (editActiveKey.value == 3) {
    let tempeleteInfoC = tempeleteInfo_C.value.getbaseForm.baseForm;
    console.log(tempeleteInfo_C.value.saveTplData, 'tempeleteInfo_C.value.saveTplData')
    tempeleteInfoC
      .validate()
      .then((res: any) => {
        console.log(res, 'eee11')
        let params = Object.assign({ id: selectSiteData.value }, tempeleteInfo_C.value.saveTplData);
        request
          .updateSiteTplList(params)
          .then((res: dataSourceType) => {
            if (res.code == "00000 00000") {
              message.success(res.message);
              getSiteDetail_extendInfo();
              getSiteDetail_tempeleteInfo();
            } else {
              message.error(res.message);
            }
          });
      })
      .catch((err: any) => {
        setTimeout(() => {
          let errors = document.querySelector(".ant-form-item-explain-error");
          if (document.querySelector(".baseInfo")?.contains(errors)) {
            editActiveKey.value = "1";
          } else if (document.querySelector(".extendInfo")?.contains(errors)) {
            editActiveKey.value = "2";
          }
          errors?.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }, 40);
      });
  }
};
//邮箱检测
const checkEmail = async () => {
  isVisible.value = true;
  console.log(extendInfo_C.value.formState, 9999)
}
const buttonMessage = async (msg: dataSourceType) => {
  //保存
  emailCheckFrom.value
    .validate()
    .then(() => {
      let params = {
        emailName: extendInfo_C.value.formState[8].children[2].value,
        emailCheck: formState.value.emailCheck.value,
        emailPassword: extendInfo_C.value.formState[8].children[3].value,
        isSsl: extendInfo_C.value.formState[8].children[4].value,
        smtpPort: extendInfo_C.value.formState[8].children[1].value,
        smtpService: extendInfo_C.value.formState[8].children[0].value
      }
      request.checkEmail(params).then((res: any) => {
        if (res.code == '00000 00000') {
          isVisible.value = false;
          message.success(res.message);
        } else {
          isVisible.value = false;
          message.error(res.message);
        }

      })
    })
}
//onMounted
onMounted(() => {
  btnPerm.value = routerPerm()
  getRdecord();
  selectSiteData.value = routeParams.id;
  getSiteDetail_baseInfo();
  useFixeWidth();
});
</script>

<style lang="less" scoped>
.siteDetail {
  background-color: #fff;
  width: 100%;
  height: calc(100% - 136px);
  padding: 16px 16px 56px 16px;

  .siteDetail-header {
    width: 100%;
    padding-bottom: 16px;
    display: flex;
    align-items: center;

    .tree-select {
      display: flex;
      width: auto;
      align-items: center;
      margin-right: 16px;

      span {
        font-size: 14px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
        margin-right: 12px;
      }

      .AtreeSelect {
        width: 144px;
        min-width: 144px;
      }

      .AtreeSelect.ant-select-open {
        width: 300px;
      }
    }

    .createStaticPage {
      margin-right: 8px;
    }

    .previewSite {
      margin-right: 8px;
    }
  }
}
</style>
<style lang="less">
.AtreeSelect .ant-select-selector {
  width: 144px;
  transition: width 0.1s cubic-bezier(0.075, 0.82, 0.165, 1);
}

.AtreeSelect.ant-select-open .ant-select-selector {
  width: 300px;
}

.siteDetail .AtreeSelect .ant-select-selector .ant-select-selection-item {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.siteInfoDetail .ant-tabs-tab {
  padding: 0px 0 8px;
}

.siteDetail .table-bottom_fiexd {
  height: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 0;
  background: #fff;
}

.siteDetail-modal .ant-modal-confirm-content {
  display: none;
}

.siteInfoDetail {
  height: 100%;
  overflow: hidden;

  .ant-tabs.ant-tabs-top {
    height: 100%;
    overflow: hidden;

    .ant-tabs-content-holder {
      height: 100%;
      overflow: hidden;

      .ant-tabs-content.ant-tabs-content-top {
        height: 100%;
        overflow: hidden;

        .ant-tabs-tabpane-active {
          height: calc(100%);
          position: relative;
          overflow: hidden;
        }

        .a-scroll {
          height: calc(100% - 80px);
          overflow-y: auto;
        }
      }
    }
  }
}
</style>
<style lang="less">
.extend_modal {
  .ant-form-item {
    margin-bottom: 0px;
  }
}
</style>
